The following ORT classes are available for instantiating a base model class without a specific head.
( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
Parameters
~onnxruntime.InferenceSession) — The ONNX Runtime InferenceSession that is running the model. — bool, optional, defaults to True) — Whether to use I/O bindings with **ONNX Runtime — Path) — The directory where the model exported to ONNX is saved. — Base class for implementing models using ONNX Runtime.
The ORTModel implements generic methods for interacting with the Hugging Face Hub as well as exporting vanilla
transformers models to ONNX using optimum.exporters.onnx toolchain.
Class attributes:
str, optional, defaults to "onnx_model") — The name of the model type to use when
registering the ORTModel classes.Type, optional, defaults to AutoModel) — The “AutoModel” class to represented by the
current ORTModel class.Returns whether this model can generate sequences with .generate().
( model_id: str | Path config: PretrainedConfig | None = None export: bool = False subfolder: str = '' revision: str = 'main' force_download: bool = False local_files_only: bool = False trust_remote_code: bool = False cache_dir: str = '/home/runner/.cache/huggingface/hub' token: bool | str | None = None provider: str = 'CPUExecutionProvider' providers: Sequence[str] | None = None provider_options: Sequence[dict[str, Any]] | dict[str, Any] | None = None session_options: SessionOptions | None = None use_io_binding: bool | None = None **kwargs ) → ORTModel
Parameters
Union[str, Path]) —
Can be either:bert-base-uncased, or namespaced under a
user or organization name, like dbmdz/bert-base-german-cased.~OptimizedModel.save_pretrained,
e.g., ./my_model_directory/.bool, defaults to False) —
Defines whether the provided model_id needs to be exported to the targeted format. bool, defaults to True) —
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist. Optional[Union[bool,str]], defaults to None) —
Deprecated. Please use the token argument instead. Optional[Union[bool,str]], defaults to None) —
The token to use as HTTP bearer authorization for remote files. If True, will use the token generated
when running huggingface-cli login (stored in huggingface_hub.constants.HF_TOKEN_PATH). Optional[str], defaults to None) —
Path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used. str, defaults to "") —
In case the relevant files are located inside a subfolder of the model repo either locally or on huggingface.co, you can
specify the folder name here. Optional[transformers.PretrainedConfig], defaults to None) —
The model configuration. Optional[bool], defaults to False) —
Whether or not to only look at local files (i.e., do not try to download the model). bool, defaults to False) —
Whether or not to allow for custom code defined on the Hub in their own modeling. This option should only be set
to True for repositories you trust and in which you have read the code, as it will execute code present on
the Hub on your local machine. Optional[str], defaults to None) —
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so revision can be any
identifier allowed by git. Returns
ORTModel
The loaded ORTModel model.
Instantiate a pretrained model from a pre-trained model configuration.
provider (str, defaults to "CPUExecutionProvider"):
ONNX Runtime provider to use for loading the model.
See https://onnxruntime.ai/docs/execution-providers/ for possible providers.
providers (Optional[Sequence[str]], defaults to None):
List of execution providers to use for loading the model.
This argument takes precedence over the provider argument.
provider_options (Optional[Dict[str, Any]], defaults to None):
Provider option dictionaries corresponding to the provider used. See available options
for each provider: https://onnxruntime.ai/docs/api/c/group___global.html .
session_options (Optional[onnxruntime.SessionOptions], defaults to None),:
ONNX Runtime session options to use for loading the model.
use_io_binding (Optional[bool], defaults to None):
Whether to use IOBinding during inference to avoid memory copy between the host and device, or between numpy/torch tensors and ONNX Runtime ORTValue. Defaults to
True if the execution provider is CUDAExecutionProvider. For [~onnxruntime.ORTModelForCausalLM], defaults to True on CPUExecutionProvider,
in all other cases defaults to False.
kwargs (Dict[str, Any]):
Will be passed to the underlying model loading methods.
Parameters for decoder models (ORTModelForCausalLM, ORTModelForSeq2SeqLM, ORTModelForSeq2SeqLM, ORTModelForSpeechSeq2Seq, ORTModelForVision2Seq)
use_cache (Optional[bool], defaults to True):
Whether or not past key/values cache should be used. Defaults to True.
Parameters for ORTModelForCausalLM
use_merged (Optional[bool], defaults to None):
whether or not to use a single ONNX that handles both the decoding without and with past key values reuse. This option defaults
to True if loading from a local repository and a merged decoder is found. When exporting with export=True,
defaults to False. This option should be set to True to minimize memory usage.
The following ORT classes are available for the following natural language processing tasks.
( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None generation_config: GenerationConfig | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX model with a causal language modeling head for ONNX Runtime inference. This class officially supports bloom, codegen, falcon, gpt2, gpt-bigcode, gptneo, gpt_neox, gptj, llama. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.LongTensor attention_mask: torch.LongTensor | None = None past_key_values: tuple[tuple[torch.Tensor]] | None = None position_ids: torch.LongTensor | None = None use_cache: bool | None = None **kwargs )
Parameters
torch.LongTensor) —
Indices of decoder input sequence tokens in the vocabulary of shape (batch_size, sequence_length). torch.LongTensor) —
Mask to avoid performing attention on padding token indices, of shape
(batch_size, sequence_length). Mask values selected in [0, 1]. tuple(tuple(torch.FloatTensor), *optional*, defaults to None) —
Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding.
The tuple is of length config.n_layers with each tuple having 2 tensors of shape
(batch_size, num_heads, sequence_length, embed_size_per_head). The ORTModelForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of text generation:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForCausalLM
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/gpt2")
>>> model = ORTModelForCausalLM.from_pretrained("optimum/gpt2")
>>> inputs = tokenizer("My name is Arthur and I live in", return_tensors="pt")
>>> gen_tokens = model.generate(**inputs,do_sample=True,temperature=0.9, min_length=20,max_length=20)
>>> tokenizer.batch_decode(gen_tokens)Example using transformers.pipelines:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/gpt2")
>>> model = ORTModelForCausalLM.from_pretrained("optimum/gpt2")
>>> onnx_gen = pipeline("text-generation", model=model, tokenizer=tokenizer)
>>> text = "My name is Arthur and I live in"
>>> gen = onnx_gen(text)( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a MaskedLMOutput for masked language modeling tasks. This class officially supports albert, bert, camembert, convbert, data2vec-text, deberta, debertav2, distilbert, electra, flaubert, ibert, mobilebert, roberta, roformer, squeezebert, xlm, xlm_roberta. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForMaskedLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of feature extraction:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForMaskedLM
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> model = ORTModelForMaskedLM.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 8, 28996]Example using transformers.pipeline:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> model = ORTModelForMaskedLM.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> fill_masker = pipeline("fill-mask", model=model, tokenizer=tokenizer)
>>> text = "The capital of France is [MASK]."
>>> pred = fill_masker(text)( *args config: PretrainedConfig = None encoder_session: InferenceSession = None decoder_session: InferenceSession = None decoder_with_past_session: InferenceSession | None = None use_io_binding: bool | None = None generation_config: GenerationConfig | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports bart, blenderbot, blenderbot-small, longt5, m2m_100, marian, mbart, mt5, pegasus, t5.
This model inherits from ~onnxruntime.modeling_ort.ORTModelForConditionalGeneration, check its documentation for the generic methods the
library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModelForConditionalGeneration.from_pretrained method.
( input_ids: torch.LongTensor = None attention_mask: torch.FloatTensor | None = None decoder_input_ids: torch.LongTensor | None = None encoder_outputs: tuple[tuple[torch.Tensor]] | None = None past_key_values: tuple[tuple[torch.Tensor]] | None = None **kwargs )
Parameters
torch.LongTensor) —
Indices of input sequence tokens in the vocabulary of shape (batch_size, encoder_sequence_length). torch.LongTensor) —
Mask to avoid performing attention on padding token indices, of shape
(batch_size, encoder_sequence_length). Mask values selected in [0, 1]. torch.LongTensor) —
Indices of decoder input sequence tokens in the vocabulary of shape (batch_size, decoder_sequence_length). torch.FloatTensor) —
The encoder last_hidden_state of shape (batch_size, encoder_sequence_length, hidden_size). tuple(tuple(torch.FloatTensor), *optional*, defaults to None) —
Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding.
The tuple is of length config.n_layers with each tuple having 2 tensors of shape
(batch_size, num_heads, decoder_sequence_length, embed_size_per_head) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The ORTModelForSeq2SeqLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of text generation:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForSeq2SeqLM
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/t5-small")
>>> model = ORTModelForSeq2SeqLM.from_pretrained("optimum/t5-small")
>>> inputs = tokenizer("My name is Eustache and I like to", return_tensors="pt")
>>> gen_tokens = model.generate(**inputs)
>>> outputs = tokenizer.batch_decode(gen_tokens)Example using transformers.pipeline:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSeq2SeqLM
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/t5-small")
>>> model = ORTModelForSeq2SeqLM.from_pretrained("optimum/t5-small")
>>> onnx_translation = pipeline("translation_en_to_de", model=model, tokenizer=tokenizer)
>>> text = "My name is Eustache."
>>> pred = onnx_translation(text)( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. This class officially supports albert, bart, bert, camembert, convbert, data2vec-text, deberta, deberta_v2, distilbert, electra, flaubert, ibert, mbart, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm_roberta.
This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForSequenceClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of single-label classification:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForSequenceClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2]Example using transformers.pipelines:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> onnx_classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
>>> text = "Hello, my dog is cute"
>>> pred = onnx_classifier(text)Example using zero-shot-classification transformers.pipelines:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-mnli")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-mnli")
>>> onnx_z0 = pipeline("zero-shot-classification", model=model, tokenizer=tokenizer)
>>> sequence_to_classify = "Who are you voting for in 2020?"
>>> candidate_labels = ["Europe", "public health", "politics", "elections"]
>>> pred = onnx_z0(sequence_to_classify, candidate_labels, multi_label=True)( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. This class officially supports albert, bert, bloom, camembert, convbert, data2vec-text, deberta, deberta_v2, distilbert, electra, flaubert, gpt2, ibert, mobilebert, roberta, roformer, squeezebert, xlm, xlm_roberta.
This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForTokenClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of token classification:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-NER")
>>> model = ORTModelForTokenClassification.from_pretrained("optimum/bert-base-NER")
>>> inputs = tokenizer("My name is Philipp and I live in Germany.", return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 12, 9]Example using transformers.pipelines:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForTokenClassification
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-NER")
>>> model = ORTModelForTokenClassification.from_pretrained("optimum/bert-base-NER")
>>> onnx_ner = pipeline("token-classification", model=model, tokenizer=tokenizer)
>>> text = "My name is Philipp and I live in Germany."
>>> pred = onnx_ner(text)( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. This class officially supports albert, bert, camembert, convbert, data2vec-text, deberta_v2, distilbert, electra, flaubert, ibert, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm_roberta.
This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForMultipleChoice forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of mutliple choice:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForMultipleChoice
>>> tokenizer = AutoTokenizer.from_pretrained("ehdwns1516/bert-base-uncased_SWAG")
>>> model = ORTModelForMultipleChoice.from_pretrained("ehdwns1516/bert-base-uncased_SWAG", export=True)
>>> num_choices = 4
>>> first_sentence = ["Members of the procession walk down the street holding small horn brass instruments."] * num_choices
>>> second_sentence = [
... "A drum line passes by walking down the street playing their instruments.",
... "A drum line has heard approaching them.",
... "A drum line arrives and they're outside dancing and asleep.",
... "A drum line turns the lead singer watches the performance."
... ]
>>> inputs = tokenizer(first_sentence, second_sentence, truncation=True, padding=True)
# Unflatten the inputs values expanding it to the shape [batch_size, num_choices, seq_length]
>>> for k, v in inputs.items():
... inputs[k] = [v[i: i + num_choices] for i in range(0, len(v), num_choices)]
>>> inputs = dict(inputs.convert_to_tensors(tensor_type="pt"))
>>> outputs = model(**inputs)
>>> logits = outputs.logits( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a QuestionAnsweringModelOutput for extractive question-answering tasks like SQuAD. This class officially supports albert, bart, bert, camembert, convbert, data2vec-text, deberta, debertav2, distilbert, electra, flaubert, gptj, ibert, mbart, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm_roberta. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForQuestionAnswering forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of question answering:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/roberta-base-squad2")
>>> model = ORTModelForQuestionAnswering.from_pretrained("optimum/roberta-base-squad2")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="np")
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])
>>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions)
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logitsExample using transformers.pipeline:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForQuestionAnswering
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/roberta-base-squad2")
>>> model = ORTModelForQuestionAnswering.from_pretrained("optimum/roberta-base-squad2")
>>> onnx_qa = pipeline("question-answering", model=model, tokenizer=tokenizer)
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> pred = onnx_qa(question, text)The following ORT classes are available for the following computer vision tasks.
( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model for image-classification tasks. This class officially supports beit, convnext, convnextv2, data2vec-vision, deit, dinov2, levit, mobilenetv1, mobilenet_v2, mobilevit, poolformer, resnet, segformer, swin, swinv2, vit. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( pixel_values: torch.Tensor | np.ndarray return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, num_channels, height, width), defaults to None) —
Pixel values corresponding to the images in the current batch.
Pixel values can be obtained from encoded images using AutoFeatureExtractor. The ORTModelForImageClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of image classification:
>>> import requests
>>> from PIL import Image
>>> from optimum.onnxruntime import ORTModelForImageClassification
>>> from transformers import AutoFeatureExtractor
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/vit-base-patch16-224")
>>> model = ORTModelForImageClassification.from_pretrained("optimum/vit-base-patch16-224")
>>> inputs = preprocessor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logitsExample using transformers.pipeline:
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForImageClassification
>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/vit-base-patch16-224")
>>> model = ORTModelForImageClassification.from_pretrained("optimum/vit-base-patch16-224")
>>> onnx_image_classifier = pipeline("image-classification", model=model, feature_extractor=preprocessor)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> pred = onnx_image_classifier(url)ONNX Model for semantic-segmentation, with an all-MLP decode head on top e.g. for ADE20k, CityScapes. This class officially supports maskformer, segformer. This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( pixel_values: torch.Tensor | np.ndarray return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, num_channels, height, width), defaults to None) —
Pixel values corresponding to the images in the current batch.
Pixel values can be obtained from encoded images using AutoFeatureExtractor. The ORTModelForSemanticSegmentation forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of semantic segmentation:
>>> import requests
>>> from PIL import Image
>>> from optimum.onnxruntime import ORTModelForSemanticSegmentation
>>> from transformers import AutoFeatureExtractor
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> model = ORTModelForSemanticSegmentation.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> inputs = preprocessor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logitsExample using transformers.pipeline:
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForSemanticSegmentation
>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> model = ORTModelForSemanticSegmentation.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> onnx_image_segmenter = pipeline("image-segmentation", model=model, feature_extractor=preprocessor)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> pred = onnx_image_segmenter(url)The following ORT classes are available for the following audio tasks.
( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model for audio-classification, with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. This class officially supports audio_spectrogram_transformer, data2vec-audio, hubert, sew, sew-d, unispeech, unispeech_sat, wavlm, wav2vec2, wav2vec2-conformer.
This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_values: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None input_features: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
torch.Tensor of shape (batch_size, sequence_length)) —
Float values of input raw speech waveform..
Input values can be obtained from audio file loaded into an array using AutoFeatureExtractor. The ORTModelForAudioClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of audio classification:
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioClassification
>>> from datasets import load_dataset
>>> import torch
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/hubert-base-superb-ks")
>>> model = ORTModelForAudioClassification.from_pretrained("optimum/hubert-base-superb-ks")
>>> # audio file is decoded on the fly
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_ids = torch.argmax(logits, dim=-1).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]Example using transformers.pipeline:
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForAudioClassification
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/hubert-base-superb-ks")
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> model = ORTModelForAudioClassification.from_pretrained("optimum/hubert-base-superb-ks")
>>> onnx_ac = pipeline("audio-classification", model=model, feature_extractor=feature_extractor)
>>> pred = onnx_ac(dataset[0]["audio"]["array"])( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a frame classification head on top for tasks like Speaker Diarization. This class officially supports data2vec-audio, unispeechsat, wavlm, wav2vec2, wav2vec2-conformer. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_values: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
torch.Tensor of shape (batch_size, sequence_length)) —
Float values of input raw speech waveform..
Input values can be obtained from audio file loaded into an array using AutoFeatureExtractor. The ORTModelForAudioFrameClassification forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of audio frame classification:
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioFrameClassification
>>> from datasets import load_dataset
>>> import torch
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/wav2vec2-base-superb-sd")
>>> model = ORTModelForAudioFrameClassification.from_pretrained("optimum/wav2vec2-base-superb-sd")
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], return_tensors="pt", sampling_rate=sampling_rate)
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> probabilities = torch.sigmoid(logits[0])
>>> labels = (probabilities > 0.5).long()
>>> labels[0].tolist()( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with a language modeling head on top for Connectionist Temporal Classification (CTC). This class officially supports data2vec-audio, hubert, sew, sew-d, unispeech, unispeechsat, wavlm, wav2vec2, wav2vec2-conformer. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_values: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
torch.Tensor of shape (batch_size, sequence_length)) —
Float values of input raw speech waveform..
Input values can be obtained from audio file loaded into an array using AutoFeatureExtractor. The ORTModelForCTC forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of CTC:
>>> from transformers import AutoProcessor, HubertForCTC
>>> from optimum.onnxruntime import ORTModelForCTC
>>> from datasets import load_dataset
>>> import torch
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate
>>> processor = AutoProcessor.from_pretrained("optimum/hubert-large-ls960-ft")
>>> model = ORTModelForCTC.from_pretrained("optimum/hubert-large-ls960-ft")
>>> # audio file is decoded on the fly
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_ids = torch.argmax(logits, dim=-1)
>>> transcription = processor.batch_decode(predicted_ids)Speech Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports whisper, speech_to_text.
This model inherits from ~onnxruntime.modeling_ort.ORTModelForConditionalGeneration, check its documentation for the generic methods the
library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModelForConditionalGeneration.from_pretrained method.
( input_features: torch.FloatTensor | None = None attention_mask: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None encoder_outputs: tuple[tuple[torch.Tensor]] | None = None past_key_values: tuple[tuple[torch.Tensor]] | None = None cache_position: torch.Tensor | None = None **kwargs )
Parameters
torch.FloatTensor) —
Mel features extracted from the raw speech waveform.
(batch_size, feature_size, encoder_sequence_length). torch.LongTensor) —
Indices of decoder input sequence tokens in the vocabulary of shape (batch_size, decoder_sequence_length). torch.FloatTensor) —
The encoder last_hidden_state of shape (batch_size, encoder_sequence_length, hidden_size). tuple(tuple(torch.FloatTensor), *optional*, defaults to None) —
Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding.
The tuple is of length config.n_layers with each tuple having 2 tensors of shape
(batch_size, num_heads, decoder_sequence_length, embed_size_per_head) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The ORTModelForSpeechSeq2Seq forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of text generation:
>>> from transformers import AutoProcessor
>>> from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
>>> from datasets import load_dataset
>>> processor = AutoProcessor.from_pretrained("optimum/whisper-tiny.en")
>>> model = ORTModelForSpeechSeq2Seq.from_pretrained("optimum/whisper-tiny.en")
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor.feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> gen_tokens = model.generate(inputs=inputs.input_features)
>>> outputs = processor.tokenizer.batch_decode(gen_tokens)Example using transformers.pipeline:
>>> from transformers import AutoProcessor, pipeline
>>> from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
>>> from datasets import load_dataset
>>> processor = AutoProcessor.from_pretrained("optimum/whisper-tiny.en")
>>> model = ORTModelForSpeechSeq2Seq.from_pretrained("optimum/whisper-tiny.en")
>>> speech_recognition = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor)
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> pred = speech_recognition(ds[0]["audio"]["array"])( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model with an XVector feature extraction head on top for tasks like Speaker Verification. This class officially supports data2vec-audio, unispeechsat, wavlm, wav2vec2, wav2vec2-conformer. This model inherits from [ORTModel](/docs/optimum/pr}/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_values: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
torch.Tensor of shape (batch_size, sequence_length)) —
Float values of input raw speech waveform..
Input values can be obtained from audio file loaded into an array using AutoFeatureExtractor. The ORTModelForAudioXVector forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of Audio XVector:
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioXVector
>>> from datasets import load_dataset
>>> import torch
>>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/wav2vec2-base-superb-sv")
>>> model = ORTModelForAudioXVector.from_pretrained("optimum/wav2vec2-base-superb-sv")
>>> # audio file is decoded on the fly
>>> inputs = feature_extractor(
... [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True
... )
>>> with torch.no_grad():
... embeddings = model(**inputs).embeddings
>>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu()
>>> cosine_sim = torch.nn.CosineSimilarity(dim=-1)
>>> similarity = cosine_sim(embeddings[0], embeddings[1])
>>> threshold = 0.7
>>> if similarity < threshold:
... print("Speakers are not the same!")
>>> round(similarity.item(), 2)The following ORT classes are available for the following multimodal tasks.
( *args config: PretrainedConfig = None encoder_session: InferenceSession = None decoder_session: InferenceSession = None decoder_with_past_session: InferenceSession | None = None use_io_binding: bool | None = None generation_config: GenerationConfig | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
VisionEncoderDecoder Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports trocr and vision-encoder-decoder.
This model inherits from ~onnxruntime.modeling_ort.ORTModelForConditionalGeneration, check its documentation for the generic methods the
library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModelForConditionalGeneration.from_pretrained method.
( pixel_values: torch.FloatTensor | None = None decoder_input_ids: torch.LongTensor | None = None encoder_outputs: tuple[tuple[torch.Tensor]] | None = None past_key_values: tuple[tuple[torch.Tensor]] | None = None **kwargs )
Parameters
torch.FloatTensor) —
Features extracted from an Image. This tensor should be of shape
(batch_size, num_channels, height, width). torch.LongTensor) —
Indices of decoder input sequence tokens in the vocabulary of shape (batch_size, decoder_sequence_length). torch.FloatTensor) —
The encoder last_hidden_state of shape (batch_size, encoder_sequence_length, hidden_size). tuple(tuple(torch.FloatTensor), *optional*, defaults to None) —
Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding.
The tuple is of length config.n_layers with each tuple having 2 tensors of shape
(batch_size, num_heads, decoder_sequence_length, embed_size_per_head) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The ORTModelForVision2Seq forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of text generation:
>>> from transformers import AutoImageProcessor, AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForVision2Seq
>>> from PIL import Image
>>> import requests
>>> processor = AutoImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> model = ORTModelForVision2Seq.from_pretrained("nlpconnect/vit-gpt2-image-captioning", export=True)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(image, return_tensors="pt")
>>> gen_tokens = model.generate(**inputs)
>>> outputs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
Example using transformers.pipeline:
>>> from transformers import AutoImageProcessor, AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForVision2Seq
>>> from PIL import Image
>>> import requests
>>> processor = AutoImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> model = ORTModelForVision2Seq.from_pretrained("nlpconnect/vit-gpt2-image-captioning", export=True)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_to_text = pipeline("image-to-text", model=model, tokenizer=tokenizer, feature_extractor=processor, image_processor=processor)
>>> pred = image_to_text(image)( *args config: PretrainedConfig = None encoder_session: InferenceSession = None decoder_session: InferenceSession = None decoder_with_past_session: InferenceSession | None = None use_io_binding: bool | None = None generation_config: GenerationConfig | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
Pix2struct model with a language modeling head for ONNX Runtime inference. This class officially supports pix2struct.
This model inherits from ~onnxruntime.modeling_ort.ORTModelForConditionalGeneration, check its documentation for the generic methods the
library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModelForConditionalGeneration.from_pretrained method.
( flattened_patches: torch.FloatTensor | None = None attention_mask: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None decoder_attention_mask: torch.BoolTensor | None = None encoder_outputs: tuple[tuple[torch.Tensor]] | None = None past_key_values: tuple[tuple[torch.Tensor]] | None = None **kwargs )
Parameters
torch.FloatTensor of shape (batch_size, seq_length, hidden_size)) —
Flattened pixel patches. the hidden_size is obtained by the following formula: hidden_size =
num_channels patch_size patch_size
The process of flattening the pixel patches is done by Pix2StructProcessor. torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. torch.LongTensor of shape (batch_size, target_sequence_length), optional) —
Indices of decoder input sequence tokens in the vocabulary.
Pix2StructText uses the pad_token_id as the starting token for decoder_input_ids generation. If
past_key_values is used, optionally only the last decoder_input_ids have to be input (see
past_key_values). torch.BoolTensor of shape (batch_size, target_sequence_length), optional) —
Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also
be used by default. tuple(tuple(torch.FloatTensor), optional) —
Tuple consists of (last_hidden_state, optional: hidden_states, optional: attentions)
last_hidden_state of shape (batch_size, sequence_length, hidden_size) is a sequence of hidden states at
the output of the last layer of the encoder. Used in the cross-attention of the decoder. tuple(tuple(torch.FloatTensor), *optional*, defaults to None) —
Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding.
The tuple is of length config.n_layers with each tuple having 2 tensors of shape
(batch_size, num_heads, decoder_sequence_length, embed_size_per_head) and 2 additional tensors of shape
(batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The ORTModelForPix2Struct forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of pix2struct:
>>> from transformers import AutoProcessor
>>> from optimum.onnxruntime import ORTModelForPix2Struct
>>> from PIL import Image
>>> import requests
>>> processor = AutoProcessor.from_pretrained("google/pix2struct-ai2d-base")
>>> model = ORTModelForPix2Struct.from_pretrained("google/pix2struct-ai2d-base", export=True, use_io_binding=True)
>>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> question = "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"
>>> inputs = processor(images=image, text=question, return_tensors="pt")
>>> gen_tokens = model.generate(**inputs)
>>> outputs = processor.batch_decode(gen_tokens, skip_special_tokens=True)The following ORT classes are available for the following custom tasks.
( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model for any custom tasks. It can be used to leverage the inference acceleration for any single-file ONNX model, that may use custom inputs and outputs. This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
The ORTModelForCustomTasks forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of custom tasks(e.g. a sentence transformers taking pooler_output as output):
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForCustomTasks
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> model = ORTModelForCustomTasks.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> inputs = tokenizer("I love burritos!", return_tensors="np")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooler_output = outputs.pooler_outputExample using transformers.pipelines(only if the task is supported):
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForCustomTasks
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> model = ORTModelForCustomTasks.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> onnx_extractor = pipeline("feature-extraction", model=model, tokenizer=tokenizer)
>>> text = "I love burritos!"
>>> pred = onnx_extractor(text)( *args config: PretrainedConfig = None session: InferenceSession = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Model for feature-extraction task. This model inherits from ORTModel, check its documentation for the generic methods the library implements for all its model (such as downloading or saving).
This class should be initialized using the onnxruntime.modeling_ort.ORTModel.from_pretrained() method.
( input_ids: torch.Tensor | np.ndarray | None = None attention_mask: torch.Tensor | np.ndarray | None = None token_type_ids: torch.Tensor | np.ndarray | None = None position_ids: torch.Tensor | np.ndarray | None = None pixel_values: torch.Tensor | np.ndarray | None = None visual_embeds: torch.Tensor | np.ndarray | None = None visual_attention_mask: torch.Tensor | np.ndarray | None = None visual_token_type_ids: torch.Tensor | np.ndarray | None = None input_features: torch.Tensor | np.ndarray | None = None input_values: torch.Tensor | np.ndarray | None = None return_dict: bool = True **kwargs )
Parameters
Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer.
See PreTrainedTokenizer.encode and
PreTrainedTokenizer.__call__ for details.
What are input IDs? Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:Union[torch.Tensor, np.ndarray, None] of shape (batch_size, sequence_length), defaults to None) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:The ORTModelForFeatureExtraction forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Example of feature extraction:
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForFeatureExtraction
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> model = ORTModelForFeatureExtraction.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> inputs = tokenizer("My name is Philipp and I live in Germany.", return_tensors="np")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> list(last_hidden_state.shape)
[1, 12, 384]Example using transformers.pipeline:
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForFeatureExtraction
>>> tokenizer = AutoTokenizer.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> model = ORTModelForFeatureExtraction.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> onnx_extractor = pipeline("feature-extraction", model=model, tokenizer=tokenizer)
>>> text = "My name is Philipp and I live in Germany."
>>> pred = onnx_extractor(text)( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.5) —
A higher guidance scale value encourages the model to generate images closely linked to the text
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1. str or List[str], optional) —
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
pass negative_prompt_embeds instead. Ignored when not using guidance (guidance_scale < 1). int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) from the DDIM paper. Only
applies to the ~schedulers.DDIMScheduler, and is ignored in other schedulers. torch.Generator or List[torch.Generator], optional) —
A torch.Generator to make
generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor is generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
provided, text embeddings are generated from the prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
not provided, negative_prompt_embeds are generated from the negative_prompt input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generated image. Choose between PIL.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined in
self.processor. float, optional, defaults to 0.0) —
Guidance rescale factor from Common Diffusion Noise Schedules and Sample Steps are
Flawed. Guidance rescale factor should fix overexposure when
using zero terminal SNR. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
The call function to the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionImg2ImgPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.8 num_inference_steps: typing.Optional[int] = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: typing.Optional[float] = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: typing.Optional[float] = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: int = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], or List[np.ndarray]) —
Image, numpy array or tensor representing an image batch to be used as the starting point. For both
numpy array and pytorch tensor, the expected value range is between [0, 1] If it’s a tensor or a list
or tensors, the expected shape should be (B, C, H, W) or (C, H, W). If it is a numpy array or a
list of arrays, the expected shape should be (B, H, W, C) or (H, W, C) It can also accept image
latents as image, but if passing latents directly it is not encoded again. float, optional, defaults to 0.8) —
Indicates extent to transform the reference image. Must be between 0 and 1. image is used as a
starting point and more noise is added the higher the strength. The number of denoising steps depends
on the amount of noise initially added. When strength is 1, added noise is maximum and the denoising
process runs for the full number of iterations specified in num_inference_steps. A value of 1
essentially ignores image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. This parameter is modulated by strength. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.5) —
A higher guidance scale value encourages the model to generate images closely linked to the text
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1. str or List[str], optional) —
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
pass negative_prompt_embeds instead. Ignored when not using guidance (guidance_scale < 1). int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) from the DDIM paper. Only
applies to the ~schedulers.DDIMScheduler, and is ignored in other schedulers. torch.Generator or List[torch.Generator], optional) —
A torch.Generator to make
generation deterministic. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
provided, text embeddings are generated from the prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
not provided, negative_prompt_embeds are generated from the negative_prompt input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generated image. Choose between PIL.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined in
self.processor. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
The call function to the pipeline for generation.
Examples:
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionImg2ImgPipeline
>>> device = "cuda"
>>> model_id_or_path = "stable-diffusion-v1-5/stable-diffusion-v1-5"
>>> pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
>>> pipe = pipe.to(device)
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))
>>> prompt = "A fantasy landscape, trending on artstation"
>>> images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
>>> images[0].save("fantasy_landscape.png")( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionInpaintPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 1.0 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: int = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], or List[np.ndarray]) —
Image, numpy array or tensor representing an image batch to be inpainted (which parts of the image to
be masked out with mask_image and repainted according to prompt). For both numpy array and pytorch
tensor, the expected value range is between [0, 1] If it’s a tensor or a list or tensors, the
expected shape should be (B, C, H, W) or (C, H, W). If it is a numpy array or a list of arrays, the
expected shape should be (B, H, W, C) or (H, W, C) It can also accept image latents as image, but
if passing latents directly it is not encoded again. torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], or List[np.ndarray]) —
Image, numpy array or tensor representing an image batch to mask image. White pixels in the mask
are repainted while black pixels are preserved. If mask_image is a PIL image, it is converted to a
single channel (luminance) before use. If it’s a numpy array or pytorch tensor, it should contain one
color channel (L) instead of 3, so the expected shape for pytorch tensor would be (B, 1, H, W), (B, H, W), (1, H, W), (H, W). And for numpy array would be for (B, H, W, 1), (B, H, W), (H, W, 1), or (H, W). int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. int, optional, defaults to None) —
The size of margin in the crop to be applied to the image and masking. If None, no crop is applied to
image and mask_image. If padding_mask_crop is not None, it will first find a rectangular region
with the same aspect ration of the image and contains all masked area, and then expand that area based
on padding_mask_crop. The image and mask_image will then be cropped based on the expanded area before
resizing to the original image size for inpainting. This is useful when the masked area is small while
the image is large and contain information irrelevant for inpainting, such as background. float, optional, defaults to 1.0) —
Indicates extent to transform the reference image. Must be between 0 and 1. image is used as a
starting point and more noise is added the higher the strength. The number of denoising steps depends
on the amount of noise initially added. When strength is 1, added noise is maximum and the denoising
process runs for the full number of iterations specified in num_inference_steps. A value of 1
essentially ignores image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. This parameter is modulated by strength. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.5) —
A higher guidance scale value encourages the model to generate images closely linked to the text
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1. str or List[str], optional) —
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
pass negative_prompt_embeds instead. Ignored when not using guidance (guidance_scale < 1). int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) from the DDIM paper. Only
applies to the ~schedulers.DDIMScheduler, and is ignored in other schedulers. torch.Generator or List[torch.Generator], optional) —
A torch.Generator to make
generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor is generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
provided, text embeddings are generated from the prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
not provided, negative_prompt_embeds are generated from the negative_prompt input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generated image. Choose between PIL.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined in
self.processor. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
The call function to the pipeline for generation.
Examples:
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO
>>> from diffusers import StableDiffusionInpaintPipeline
>>> def download_image(url):
... response = requests.get(url)
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = download_image(img_url).resize((512, 512))
>>> mask_image = download_image(mask_url).resize((512, 512))
>>> pipe = StableDiffusionInpaintPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionXLPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to the tokenizer_2 and text_encoder_2. If not defined, prompt is
used in both text-encoders int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results.
Anything below 512 pixels won’t work well for
stabilityai/stable-diffusion-xl-base-1.0
and checkpoints that are not specifically fine-tuned on low resolutions. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results.
Anything below 512 pixels won’t work well for
stabilityai/stable-diffusion-xl-base-1.0
and checkpoints that are not specifically fine-tuned on low resolutions. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional) —
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
completed before it is intentionally prematurely terminated. As a result, the returned sample will
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
“Mixture of Denoisers” multi-pipeline setup, as elaborated in Refining the Image
Output float, optional, defaults to 5.0) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used in both text-encoders int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
applies to schedulers.DDIMScheduler, will be ignored for others. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.Tensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput instead
of a plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. float, optional, defaults to 0.0) —
Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are
Flawed guidance_scale is defined as φ in equation 16. of
Common Diffusion Noise Schedules and Sample Steps are
Flawed. Guidance rescale factor should fix overexposure when
using zero terminal SNR. Tuple[int], optional, defaults to (1024, 1024)) —
If original_size is not the same as target_size the image will appear to be down- or upsampled.
original_size defaults to (height, width) if not specified. Part of SDXL’s micro-conditioning as
explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (0, 0)) —
crops_coords_top_left can be used to generate an image that appears to be “cropped” from the position
crops_coords_top_left downwards. Favorable, well-centered images are usually achieved by setting
crops_coords_top_left to (0, 0). Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
For most cases, target_size should be set to the desired height and width of the generated image. If
not specified it will default to (height, width). Part of SDXL’s micro-conditioning as explained in
section 2.2 of https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a specific image resolution. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (0, 0)) —
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a target image resolution. It should be as same
as the target_size for most cases. Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput or tuple
~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput if return_dict is True, otherwise a
tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusionXLPipeline
>>> pipe = StableDiffusionXLPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionXLImg2ImgPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.3 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to the tokenizer_2 and text_encoder_2. If not defined, prompt is
used in both text-encoders torch.Tensor or PIL.Image.Image or np.ndarray or List[torch.Tensor] or List[PIL.Image.Image] or List[np.ndarray]) —
The image(s) to modify with the pipeline. float, optional, defaults to 0.3) —
Conceptually, indicates how much to transform the reference image. Must be between 0 and 1. image
will be used as a starting point, adding more noise to it the larger the strength. The number of
denoising steps depends on the amount of noise initially added. When strength is 1, added noise will
be maximum and the denoising process will run for the full number of iterations specified in
num_inference_steps. A value of 1, therefore, essentially ignores image. Note that in the case of
denoising_start being declared as an integer, the value of strength will be ignored. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional) —
When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
it is assumed that the passed image is a partly denoised image. Note that when this is specified,
strength will be ignored. The denoising_start parameter is particularly beneficial when this pipeline
is integrated into a “Mixture of Denoisers” multi-pipeline setup, as detailed in Refine Image
Quality. float, optional) —
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
completed before it is intentionally prematurely terminated. As a result, the returned sample will
still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
denoised by a successor pipeline that has denoising_start set to 0.8 so that it only denoises the
final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
forms a part of a “Mixture of Denoisers” multi-pipeline setup, as elaborated in Refine Image
Quality. float, optional, defaults to 7.5) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used in both text-encoders int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
applies to schedulers.DDIMScheduler, will be ignored for others. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.Tensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. float, optional, defaults to 0.0) —
Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are
Flawed guidance_scale is defined as φ in equation 16. of
Common Diffusion Noise Schedules and Sample Steps are
Flawed. Guidance rescale factor should fix overexposure when
using zero terminal SNR. Tuple[int], optional, defaults to (1024, 1024)) —
If original_size is not the same as target_size the image will appear to be down- or upsampled.
original_size defaults to (height, width) if not specified. Part of SDXL’s micro-conditioning as
explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (0, 0)) —
crops_coords_top_left can be used to generate an image that appears to be “cropped” from the position
crops_coords_top_left downwards. Favorable, well-centered images are usually achieved by setting
crops_coords_top_left to (0, 0). Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
For most cases, target_size should be set to the desired height and width of the generated image. If
not specified it will default to (height, width). Part of SDXL’s micro-conditioning as explained in
section 2.2 of https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a specific image resolution. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (0, 0)) —
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a target image resolution. It should be as same
as the target_size for most cases. Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. float, optional, defaults to 6.0) —
Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. float, optional, defaults to 2.5) —
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Can be used to
simulate an aesthetic score of the generated image by influencing the negative text condition. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput if return_dict is True, otherwise a
`tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusionXLImg2ImgPipeline
>>> from diffusers.utils import load_image
>>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionXLInpaintPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: Tensor = None height: typing.Optional[int] = None width: typing.Optional[int] = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.9999 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to the tokenizer_2 and text_encoder_2. If not defined, prompt is
used in both text-encoders PIL.Image.Image) —
Image, or tensor representing an image batch which will be inpainted, i.e. parts of the image will
be masked out with mask_image and repainted according to prompt. PIL.Image.Image) —
Image, or tensor representing an image batch, to mask image. White pixels in the mask will be
repainted, while black pixels will be preserved. If mask_image is a PIL image, it will be converted
to a single channel (luminance) before use. If it’s a tensor, it should contain one color channel (L)
instead of 3, so the expected shape would be (B, H, W, 1). int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results.
Anything below 512 pixels won’t work well for
stabilityai/stable-diffusion-xl-base-1.0
and checkpoints that are not specifically fine-tuned on low resolutions. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results.
Anything below 512 pixels won’t work well for
stabilityai/stable-diffusion-xl-base-1.0
and checkpoints that are not specifically fine-tuned on low resolutions. int, optional, defaults to None) —
The size of margin in the crop to be applied to the image and masking. If None, no crop is applied to
image and mask_image. If padding_mask_crop is not None, it will first find a rectangular region
with the same aspect ration of the image and contains all masked area, and then expand that area based
on padding_mask_crop. The image and mask_image will then be cropped based on the expanded area before
resizing to the original image size for inpainting. This is useful when the masked area is small while
the image is large and contain information irrelevant for inpainting, such as background. float, optional, defaults to 0.9999) —
Conceptually, indicates how much to transform the masked portion of the reference image. Must be
between 0 and 1. image will be used as a starting point, adding more noise to it the larger the
strength. The number of denoising steps depends on the amount of noise initially added. When
strength is 1, added noise will be maximum and the denoising process will run for the full number of
iterations specified in num_inference_steps. A value of 1, therefore, essentially ignores the masked
portion of the reference image. Note that in the case of denoising_start being declared as an
integer, the value of strength will be ignored. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional) —
When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
it is assumed that the passed image is a partly denoised image. Note that when this is specified,
strength will be ignored. The denoising_start parameter is particularly beneficial when this pipeline
is integrated into a “Mixture of Denoisers” multi-pipeline setup, as detailed in Refining the Image
Output. float, optional) —
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
completed before it is intentionally prematurely terminated. As a result, the returned sample will
still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
denoised by a successor pipeline that has denoising_start set to 0.8 so that it only denoises the
final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
forms a part of a “Mixture of Denoisers” multi-pipeline setup, as elaborated in Refining the Image
Output. float, optional, defaults to 7.5) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used in both text-encoders torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.Tensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
applies to schedulers.DDIMScheduler, will be ignored for others. torch.Generator, optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. Tuple[int], optional, defaults to (1024, 1024)) —
If original_size is not the same as target_size the image will appear to be down- or upsampled.
original_size defaults to (height, width) if not specified. Part of SDXL’s micro-conditioning as
explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (0, 0)) —
crops_coords_top_left can be used to generate an image that appears to be “cropped” from the position
crops_coords_top_left downwards. Favorable, well-centered images are usually achieved by setting
crops_coords_top_left to (0, 0). Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
For most cases, target_size should be set to the desired height and width of the generated image. If
not specified it will default to (height, width). Part of SDXL’s micro-conditioning as explained in
section 2.2 of https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a specific image resolution. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (0, 0)) —
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a target image resolution. It should be as same
as the target_size for most cases. Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. float, optional, defaults to 6.0) —
Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. float, optional, defaults to 2.5) —
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Can be used to
simulate an aesthetic score of the generated image by influencing the negative text condition. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput if return_dict is True, otherwise a
tuple. tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusionXLInpaintPipeline
>>> from diffusers.utils import load_image
>>> pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0",
... torch_dtype=torch.float16,
... variant="fp16",
... use_safetensors=True,
... )
>>> pipe.to("cuda")
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> init_image = load_image(img_url).convert("RGB")
>>> mask_image = load_image(mask_url).convert("RGB")
>>> prompt = "A majestic tiger sitting on a bench"
>>> image = pipe(
... prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80
... ).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusionXLImg2ImgPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.3 num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_start: typing.Optional[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Tuple[int, int] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Tuple[int, int] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None aesthetic_score: float = 6.0 negative_aesthetic_score: float = 2.5 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to the tokenizer_2 and text_encoder_2. If not defined, prompt is
used in both text-encoders torch.Tensor or PIL.Image.Image or np.ndarray or List[torch.Tensor] or List[PIL.Image.Image] or List[np.ndarray]) —
The image(s) to modify with the pipeline. float, optional, defaults to 0.3) —
Conceptually, indicates how much to transform the reference image. Must be between 0 and 1. image
will be used as a starting point, adding more noise to it the larger the strength. The number of
denoising steps depends on the amount of noise initially added. When strength is 1, added noise will
be maximum and the denoising process will run for the full number of iterations specified in
num_inference_steps. A value of 1, therefore, essentially ignores image. Note that in the case of
denoising_start being declared as an integer, the value of strength will be ignored. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[int], optional) —
Custom timesteps to use for the denoising process with schedulers which support a timesteps argument
in their set_timesteps method. If not defined, the default behavior when num_inference_steps is
passed will be used. Must be in descending order. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional) —
When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
it is assumed that the passed image is a partly denoised image. Note that when this is specified,
strength will be ignored. The denoising_start parameter is particularly beneficial when this pipeline
is integrated into a “Mixture of Denoisers” multi-pipeline setup, as detailed in Refine Image
Quality. float, optional) —
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
completed before it is intentionally prematurely terminated. As a result, the returned sample will
still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
denoised by a successor pipeline that has denoising_start set to 0.8 so that it only denoises the
final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
forms a part of a “Mixture of Denoisers” multi-pipeline setup, as elaborated in Refine Image
Quality. float, optional, defaults to 7.5) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used in both text-encoders int, optional, defaults to 1) —
The number of images to generate per prompt. float, optional, defaults to 0.0) —
Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
applies to schedulers.DDIMScheduler, will be ignored for others. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.Tensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.Tensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. float, optional, defaults to 0.0) —
Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are
Flawed guidance_scale is defined as φ in equation 16. of
Common Diffusion Noise Schedules and Sample Steps are
Flawed. Guidance rescale factor should fix overexposure when
using zero terminal SNR. Tuple[int], optional, defaults to (1024, 1024)) —
If original_size is not the same as target_size the image will appear to be down- or upsampled.
original_size defaults to (height, width) if not specified. Part of SDXL’s micro-conditioning as
explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (0, 0)) —
crops_coords_top_left can be used to generate an image that appears to be “cropped” from the position
crops_coords_top_left downwards. Favorable, well-centered images are usually achieved by setting
crops_coords_top_left to (0, 0). Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
For most cases, target_size should be set to the desired height and width of the generated image. If
not specified it will default to (height, width). Part of SDXL’s micro-conditioning as explained in
section 2.2 of https://huggingface.co/papers/2307.01952. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a specific image resolution. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (0, 0)) —
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL’s
micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. Tuple[int], optional, defaults to (1024, 1024)) —
To negatively condition the generation process based on a target image resolution. It should be as same
as the target_size for most cases. Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. For more
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. float, optional, defaults to 6.0) —
Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. float, optional, defaults to 2.5) —
Part of SDXL’s micro-conditioning as explained in section 2.2 of
https://huggingface.co/papers/2307.01952. Can be used to
simulate an aesthetic score of the generated image by influencing the negative text condition. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, PipelineCallback, MultiPipelineCallbacks, optional) —
A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of
each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a
list of all tensors as specified by callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput or tuple
~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput if return_dict is True, otherwise a
`tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusionXLImg2ImgPipeline
>>> from diffusers.utils import load_image
>>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
>>> init_image = load_image(url).convert("RGB")
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> image = pipe(prompt, image=init_image).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.LatentConsistencyModelPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 4 original_inference_steps: int = None timesteps: typing.List[int] = None guidance_scale: float = 8.5 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. int, optional) —
The original number of inference steps use to generate a linearly-spaced timestep schedule, from which
we will draw num_inference_steps evenly spaced timesteps from as our final timestep schedule,
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
scheduler’s original_inference_steps attribute. List[int], optional) —
Custom timesteps to use for the denoising process. If not defined, equal spaced num_inference_steps
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
order. float, optional, defaults to 7.5) —
A higher guidance scale value encourages the model to generate images closely linked to the text
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1.
Note that the original latent consistency models paper uses a different CFG formulation where the
guidance scales are decreased by 1 (so in the paper formulation CFG is enabled when guidance_scale > 0). int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
A torch.Generator to make
generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor is generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
provided, text embeddings are generated from the prompt input argument. PipelineImageInput, optional):
Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generated image. Choose between PIL.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined in
self.processor. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
The call function to the pipeline for generation.
Examples:
>>> from diffusers import DiffusionPipeline
>>> import torch
>>> pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)
>>> prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=8.0).images
>>> images[0].save("image.png")( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.LatentConsistencyModelImg2ImgPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None num_inference_steps: int = 4 strength: float = 0.8 original_inference_steps: int = None timesteps: typing.List[int] = None guidance_scale: float = 8.5 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] **kwargs ) → ~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. int, optional) —
The original number of inference steps use to generate a linearly-spaced timestep schedule, from which
we will draw num_inference_steps evenly spaced timesteps from as our final timestep schedule,
following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
scheduler’s original_inference_steps attribute. List[int], optional) —
Custom timesteps to use for the denoising process. If not defined, equal spaced num_inference_steps
timesteps on the original LCM training/distillation timestep schedule are used. Must be in descending
order. float, optional, defaults to 7.5) —
A higher guidance scale value encourages the model to generate images closely linked to the text
prompt at the expense of lower image quality. Guidance scale is enabled when guidance_scale > 1.
Note that the original latent consistency models paper uses a different CFG formulation where the
guidance scales are decreased by 1 (so in the paper formulation CFG is enabled when guidance_scale > 0). int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
A torch.Generator to make
generation deterministic. torch.Tensor, optional) —
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor is generated by sampling using the supplied random generator. torch.Tensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
provided, text embeddings are generated from the prompt input argument. PipelineImageInput, optional):
Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). It should
contain the negative image embedding if do_classifier_free_guidance is set to True. If not
provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generated image. Choose between PIL.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion.StableDiffusionPipelineOutput instead of a
plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined in
self.processor. int, optional) —
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
the output of the pre-final layer will be used for computing the prompt embeddings. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. Returns
~pipelines.stable_diffusion.StableDiffusionPipelineOutput or tuple
If return_dict is True, ~pipelines.stable_diffusion.StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
The call function to the pipeline for generation.
Examples:
>>> from diffusers import AutoPipelineForImage2Image
>>> import torch
>>> import PIL
>>> pipe = AutoPipelineForImage2Image.from_pretrained("SimianLuo/LCM_Dreamshaper_v7")
>>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
>>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)
>>> prompt = "High altitude snowy mountains"
>>> image = PIL.Image.open("./snowy_mountains.png")
>>> # Can be set to 1~50 steps. LCM support fast inference even <= 4 steps. Recommend: 1~8 steps.
>>> num_inference_steps = 4
>>> images = pipe(
... prompt=prompt, image=image, num_inference_steps=num_inference_steps, guidance_scale=8.0
... ).images
>>> images[0].save("image.png")( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusion3Pipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 skip_guidance_layers: typing.List[int] = None skip_layer_guidance_scale: float = 2.8 skip_layer_guidance_stop: float = 0.2 skip_layer_guidance_start: float = 0.01 mu: typing.Optional[float] = None ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_2 and text_encoder_2. If not defined, prompt is
will be used instead str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_3 and text_encoder_3. If not defined, prompt is
will be used instead int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.0) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used instead str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_3 and
text_encoder_3. If not defined, negative_prompt is used instead int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.FloatTensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.FloatTensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.FloatTensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional) —
Optional image input to work with IP Adapters. torch.Tensor, optional) —
Pre-generated image embeddings for IP-Adapter. Should be a tensor of shape (batch_size, num_images, emb_dim). It should contain the negative image embedding if do_classifier_free_guidance is set to
True. If not provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput instead of
a plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. int defaults to 256) — Maximum sequence length to use with the prompt. List[int], optional) —
A list of integers that specify layers to skip during guidance. If not provided, all layers will be
used for guidance. If provided, the guidance will only be applied to the layers specified in the list.
Recommended value by StabiltyAI for Stable Diffusion 3.5 Medium is [7, 8, 9]. int, optional) — The scale of the guidance for the layers specified in
skip_guidance_layers. The guidance will be applied to the layers specified in skip_guidance_layers
with a scale of skip_layer_guidance_scale. The guidance will be applied to the rest of the layers
with a scale of 1. int, optional) — The step at which the guidance for the layers specified in
skip_guidance_layers will stop. The guidance will be applied to the layers specified in
skip_guidance_layers until the fraction specified in skip_layer_guidance_stop. Recommended value by
StabiltyAI for Stable Diffusion 3.5 Medium is 0.2. int, optional) — The step at which the guidance for the layers specified in
skip_guidance_layers will start. The guidance will be applied to the layers specified in
skip_guidance_layers from the fraction specified in skip_layer_guidance_start. Recommended value by
StabiltyAI for Stable Diffusion 3.5 Medium is 0.01. float, optional) — mu value used for dynamic_shifting. Returns
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput if return_dict is True, otherwise a
tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusion3Pipeline
>>> pipe = StableDiffusion3Pipeline.from_pretrained(
... "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> image = pipe(prompt).images[0]
>>> image.save("sd3.png")( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusion3Img2ImgPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None strength: float = 0.6 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 mu: typing.Optional[float] = None ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_2 and text_encoder_2. If not defined, prompt is
will be used instead str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_3 and text_encoder_3. If not defined, prompt is
will be used instead int, optional, defaults to self.transformer.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to self.transformer.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.0) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used instead str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_3 and
text_encoder_3. If not defined, negative_prompt is used instead int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.FloatTensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.FloatTensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.FloatTensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional) —
Optional image input to work with IP Adapters. torch.Tensor, optional) —
Pre-generated image embeddings for IP-Adapter. Should be a tensor of shape (batch_size, num_images, emb_dim). It should contain the negative image embedding if do_classifier_free_guidance is set to
True. If not provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput instead of
a plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. int defaults to 256) — Maximum sequence length to use with the prompt. float, optional) — mu value used for dynamic_shifting. Returns
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput if return_dict is True, otherwise a
tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import AutoPipelineForImage2Image
>>> from diffusers.utils import load_image
>>> device = "cuda"
>>> model_id_or_path = "stabilityai/stable-diffusion-3-medium-diffusers"
>>> pipe = AutoPipelineForImage2Image.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
>>> pipe = pipe.to(device)
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> init_image = load_image(url).resize((1024, 1024))
>>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
>>> images = pipe(prompt=prompt, image=init_image, strength=0.95, guidance_scale=7.5).images[0]( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.StableDiffusion3InpaintPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None prompt_3: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: int = None width: int = None padding_mask_crop: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 50 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_3: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 256 mu: typing.Optional[float] = None ) → ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_2 and text_encoder_2. If not defined, prompt is
will be used instead str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_3 and text_encoder_3. If not defined, prompt is
will be used instead torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], or List[np.ndarray]) —
Image, numpy array or tensor representing an image batch to be used as the starting point. For both
numpy array and pytorch tensor, the expected value range is between [0, 1] If it’s a tensor or a list
or tensors, the expected shape should be (B, C, H, W) or (C, H, W). If it is a numpy array or a
list of arrays, the expected shape should be (B, H, W, C) or (H, W, C) It can also accept image
latents as image, but if passing latents directly it is not encoded again. torch.Tensor, PIL.Image.Image, np.ndarray, List[torch.Tensor], List[PIL.Image.Image], or List[np.ndarray]) —
Image, numpy array or tensor representing an image batch to mask image. White pixels in the mask
are repainted while black pixels are preserved. If mask_image is a PIL image, it is converted to a
single channel (luminance) before use. If it’s a numpy array or pytorch tensor, it should contain one
color channel (L) instead of 3, so the expected shape for pytorch tensor would be (B, 1, H, W), (B, H, W), (1, H, W), (H, W). And for numpy array would be for (B, H, W, 1), (B, H, W), (H, W, 1), or (H, W). torch.Tensor, List[torch.Tensor]) —
Tensor representing an image batch to mask image generated by VAE. If not provided, the mask
latents tensor will ge generated by mask_image. int, optional, defaults to self.transformer.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to self.transformer.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to None) —
The size of margin in the crop to be applied to the image and masking. If None, no crop is applied to
image and mask_image. If padding_mask_crop is not None, it will first find a rectangular region
with the same aspect ration of the image and contains all masked area, and then expand that area based
on padding_mask_crop. The image and mask_image will then be cropped based on the expanded area before
resizing to the original image size for inpainting. This is useful when the masked area is small while
the image is large and contain information irrelevant for inpainting, such as background. float, optional, defaults to 1.0) —
Indicates extent to transform the reference image. Must be between 0 and 1. image is used as a
starting point and more noise is added the higher the strength. The number of denoising steps depends
on the amount of noise initially added. When strength is 1, added noise is maximum and the denoising
process runs for the full number of iterations specified in num_inference_steps. A value of 1
essentially ignores image. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 7.0) —
Guidance scale as defined in Classifier-Free Diffusion
Guidance. guidance_scale is defined as w of equation 2.
of Imagen Paper. Guidance scale is enabled by setting
guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to
the text prompt, usually at the expense of lower image quality. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is
less than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used instead str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_3 and
text_encoder_3. If not defined, negative_prompt is used instead int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.FloatTensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random generator. torch.FloatTensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.FloatTensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. PipelineImageInput, optional) —
Optional image input to work with IP Adapters. torch.Tensor, optional) —
Pre-generated image embeddings for IP-Adapter. Should be a tensor of shape (batch_size, num_images, emb_dim). It should contain the negative image embedding if do_classifier_free_guidance is set to
True. If not provided, embeddings are computed from the ip_adapter_image input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput instead of
a plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. int defaults to 256) — Maximum sequence length to use with the prompt. float, optional) — mu value used for dynamic_shifting. Returns
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput or tuple
~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput if return_dict is True, otherwise a
tuple. When returning a tuple, the first element is a list with the generated images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import StableDiffusion3InpaintPipeline
>>> from diffusers.utils import load_image
>>> pipe = StableDiffusion3InpaintPipeline.from_pretrained(
... "stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16
... )
>>> pipe.to("cuda")
>>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
>>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
>>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
>>> source = load_image(img_url)
>>> mask = load_image(mask_url)
>>> image = pipe(prompt=prompt, image=source, mask_image=mask).images[0]
>>> image.save("sd3_inpainting.png")( unet_session: InferenceSession | None = None transformer_session: InferenceSession | None = None vae_decoder_session: InferenceSession | None = None vae_encoder_session: InferenceSession | None = None text_encoder_session: InferenceSession | None = None text_encoder_2_session: InferenceSession | None = None text_encoder_3_session: InferenceSession | None = None scheduler: SchedulerMixin | None = None tokenizer: CLIPTokenizer | None = None tokenizer_2: CLIPTokenizer | None = None tokenizer_3: CLIPTokenizer | None = None feature_extractor: CLIPFeatureExtractor | None = None force_zeros_for_empty_prompt: bool = True requires_aesthetics_score: bool = False add_watermarker: bool | None = None use_io_binding: bool | None = None model_save_dir: str | Path | TemporaryDirectory | None = None **kwargs )
ONNX Runtime-powered stable diffusion pipeline corresponding to diffusers.FluxPipeline.
This Pipeline inherits from ORTDiffusionPipeline and is used to run inference with the ONNX Runtime.
The pipeline can be loaded from a pretrained pipeline using the ORTDiffusionPipeline.from_pretrained method.
( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None true_cfg_scale: float = 1.0 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 3.5 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None negative_ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput or tuple
Parameters
str or List[str], optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds.
instead. str or List[str], optional) —
The prompt or prompts to be sent to tokenizer_2 and text_encoder_2. If not defined, prompt is
will be used instead. str or List[str], optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if true_cfg_scale is
not greater than 1). str or List[str], optional) —
The prompt or prompts not to guide the image generation to be sent to tokenizer_2 and
text_encoder_2. If not defined, negative_prompt is used in all the text-encoders. float, optional, defaults to 1.0) —
True classifier-free guidance (guidance scale) is enabled when true_cfg_scale > 1 and
negative_prompt is provided. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The height in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to self.unet.config.sample_size * self.vae_scale_factor) —
The width in pixels of the generated image. This is set to 1024 by default for the best results. int, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference. List[float], optional) —
Custom sigmas to use for the denoising process with schedulers which support a sigmas argument in
their set_timesteps method. If not defined, the default behavior when num_inference_steps is passed
will be used. float, optional, defaults to 3.5) —
Embedded guiddance scale is enabled by setting guidance_scale > 1. Higher guidance_scale encourages
a model to generate images more aligned with prompt at the expense of lower image quality.
Guidance-distilled models approximates true classifer-free guidance for guidance_scale > 1. Refer to
the paper to learn more.
int, optional, defaults to 1) —
The number of images to generate per prompt. torch.Generator or List[torch.Generator], optional) —
One or a list of torch generator(s)
to make generation deterministic. torch.FloatTensor, optional) —
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will be generated by sampling using the supplied random generator. torch.FloatTensor, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt input argument. torch.FloatTensor, optional) —
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting.
If not provided, pooled text embeddings will be generated from prompt input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). If not
provided, embeddings are computed from the ip_adapter_image input argument. PipelineImageInput, optional): Optional image input to work with IP Adapters. List[torch.Tensor], optional) —
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
IP-adapters. Each element should be a tensor of shape (batch_size, num_images, emb_dim). If not
provided, embeddings are computed from the ip_adapter_image input argument. torch.FloatTensor, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input
argument. torch.FloatTensor, optional) —
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, pooled negative_prompt_embeds will be generated from negative_prompt
input argument. str, optional, defaults to "pil") —
The output format of the generate image. Choose between
PIL: PIL.Image.Image or np.array. bool, optional, defaults to True) —
Whether or not to return a ~pipelines.flux.FluxPipelineOutput instead of a plain tuple. dict, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under
self.processor in
diffusers.models.attention_processor. Callable, optional) —
A function that calls at the end of each denoising steps during the inference. The function is called
with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by
callback_on_step_end_tensor_inputs. List, optional) —
The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list
will be passed as callback_kwargs argument. You will only be able to include variables listed in the
._callback_tensor_inputs attribute of your pipeline class. int defaults to 512) — Maximum sequence length to use with the prompt. Returns
~pipelines.flux.FluxPipelineOutput or tuple
~pipelines.flux.FluxPipelineOutput if return_dict
is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated
images.
Function invoked when calling the pipeline for generation.
Examples:
>>> import torch
>>> from diffusers import FluxPipeline
>>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
>>> image.save("flux.png")